import type { WatermarkProps } from '@/types/watermark'
import React, { useEffect, useRef, useState } from 'react'
import { useResponsiveFontSize } from './useResponsiveFontSize'
import styles from './watermark.less'

const FONT_SIZE_RATIO = 0.02

/**
 * 模糊背景水印组件
 * @description 使用图片压缩模糊作为背景，支持参数自适应
 */
const BlurredImageWatermark: React.FC<
  WatermarkProps & { fontSizeRatio?: number; paddingEm?: number }
> = ({
  image,
  watermarkConfig,
  deviceModel,
  containerRef,
  fontSizeRatio = 1,
  paddingEm = 2 // 默认2em
}) => {
  // 默认不显示镜头和日期信息
  const mergedConfig = {
    showLensInfo: false,
    showDateTime: false,
    ...watermarkConfig
  }
  const [optimizedImage, setOptimizedImage] = useState<string>('')
  const imgRef = useRef<HTMLImageElement>(null)
  const watermarkRef = useRef<HTMLDivElement>(null)

  useResponsiveFontSize(imgRef, watermarkRef, FONT_SIZE_RATIO * fontSizeRatio)

  // 图片压缩函数 - 只用于模糊背景
  const compressImage = (imgSrc: string): Promise<string> => {
    return new Promise((resolve) => {
      const img = new Image()
      img.onload = () => {
        const canvas = document.createElement('canvas')
        const MAX_WIDTH = 400
        const scale = MAX_WIDTH / img.width
        const scaledHeight = img.height * scale
        canvas.width = MAX_WIDTH
        canvas.height = scaledHeight
        const ctx = canvas.getContext('2d')
        ctx?.drawImage(img, 0, 0, MAX_WIDTH, scaledHeight)
        const compressedImageUrl = canvas.toDataURL('image/jpeg', 0.4)
        resolve(compressedImageUrl)
      }
      img.src = imgSrc
    })
  }

  // 当原图更新时，生成压缩版本
  useEffect(() => {
    if (image) {
      compressImage(image).then((compressed) => {
        setOptimizedImage(compressed)
      })
    }
  }, [image])

  // 使用优化后的图片只用于模糊背景
  const backgroundImage = optimizedImage || image || ''
  const sideMargin = `${paddingEm}em`
  const topMargin = `${paddingEm}em`

  // 格式化日期 - 使用传入的日期信息
  const formatDate = (dateString: string | undefined): string => {
    if (!dateString) return ''
    try {
      const date = new Date(dateString)
      if (isNaN(date.getTime())) {
        return dateString
      }
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    } catch (error) {
      console.error('日期格式化错误', error)
      return dateString
    }
  }

  return (
    <div
      ref={containerRef}
      className={styles.imageContainer}
      style={{
        position: 'relative',
        width: '100%',
        margin: '0 auto',
        padding: `${topMargin} ${sideMargin}`,
        overflow: 'hidden'
      }}
    >
      {/* 模糊背景区域 - 使用压缩图片进行模糊处理 */}
      <div
        className={styles.blurredBorder}
        style={{
          position: 'absolute',
          top: `-${paddingEm * 0.65}em`,
          left: `-${paddingEm * 0.65}em`,
          right: `-${paddingEm * 0.65}em`,
          bottom: `-${paddingEm * 0.65}em`,
          backgroundImage: `url(${backgroundImage})`,
          backgroundSize: '300% auto',
          backgroundPosition: 'center',
          filter: `blur(2em) brightness(0.8)`,
          zIndex: 1
        }}
      />
      {/* 原始图片容器 - 使用原图 */}
      <div style={{ position: 'relative', zIndex: 3 }}>
        <img
          ref={imgRef}
          src={image || ''}
          alt="Preview"
          className={styles.originalImage}
          style={{ display: 'block', width: '100%', height: 'auto', objectFit: 'contain' }}
        />
      </div>
      {/* 水印信息容器 - 放在模糊边框内，位于照片下方 */}
      <div
        ref={watermarkRef}
        className={styles.watermarkContent}
        style={{
          zIndex: 2,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-start'
        }}
      >
        <div className={styles.photographText}>
          <div className={styles.brand}>
            <span className={styles.createdBy}>CREATED BY</span>
            <span className={styles.brandName}>{deviceModel}</span>
          </div>
          <div className={styles.photographLine}>PHOTOGRAPH</div>
        </div>
        {/* 镜头信息 - 从props中获取 */}
        {mergedConfig.showLensInfo && mergedConfig.lensInfo && (
          <div className={styles.lensInfo} style={{ marginTop: '10px', color: '#fff' }}>
            <span style={{ fontSize: '14px', fontWeight: 'bold' }}>{mergedConfig.lensInfo}</span>
          </div>
        )}
        {/* 拍摄日期 - 从props中获取 */}
        {mergedConfig.showDateTime && mergedConfig.dateTime && (
          <div
            className={styles.dateInfo}
            style={{ marginTop: '5px', color: '#ddd', fontSize: '12px' }}
          >
            {formatDate(mergedConfig.dateTime)}
          </div>
        )}
        <div className={styles.exifInfoThemed} style={{ marginTop: '15px' }}>
          <div className={styles.exifValues}>
            {mergedConfig.showISO && (
              <>
                <div className={styles.exifValue}>
                  <span className={styles.value}>
                    {mergedConfig.exifData.iso?.replace('ISO', '')}
                  </span>
                  <span className={styles.label}>ISO</span>
                </div>
                <div className={styles.exifSeparator}></div>
              </>
            )}
            {mergedConfig.showAperture && (
              <>
                <div className={styles.exifValue}>
                  <span className={styles.value}>
                    {mergedConfig.exifData.aperture?.replace('F', '')}
                  </span>
                  <span className={styles.label}>F</span>
                </div>
                <div className={styles.exifSeparator}></div>
              </>
            )}
            {mergedConfig.showFocalLength && (
              <>
                <div className={styles.exifValue}>
                  <span className={styles.value}>
                    {mergedConfig.exifData.focalLength?.replace('mm', '')}
                  </span>
                  <span className={styles.label}>mm</span>
                </div>
                <div className={styles.exifSeparator}></div>
              </>
            )}
            {mergedConfig.showShutter && (
              <div className={styles.exifValue}>
                <span className={styles.value}>
                  {mergedConfig.exifData.shutterSpeed?.replace('s', '').replace('1/', '')}
                </span>
                <span className={styles.label}>S</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export default BlurredImageWatermark
